import { useEffect, useState } from "react";
import * as echarts from "echarts";
import { random, cloneDeep } from "lodash";
// 所有hooks函数都是以use开头

function App() {
    const [count, setCount] = useState(0);
    const [option, setOption] = useState({
        title: { text: "ECharts 入门示例" },
        tooltip: {},
        xAxis: {
            data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],
        },
        yAxis: {},
        series: [
            {
                name: "销量",
                type: "bar",
                data: [5, 20, 36, 10, 10, 20],
            },
        ],
    });
    const [chart, setChart] = useState(null);
    // 构造echarts实例
    useEffect(() => {
        const chart = echarts.init(document.getElementById("chart"));
        setChart(chart);
        const handleResize = () => {
            chart.resize();
        };
        window.addEventListener("resize", handleResize);
        return () => {
            // componentWillUnmount
            window.removeEventListener("resize", handleResize);
            chart.dispose();
        };
    }, []);
    useEffect(() => {
        // chart最开始null -> setOption
        chart && chart.setOption(option);
    }, [chart, JSON.stringify(option)]);

    // useEffect(() => {
    //     console.log("count1:", count);
    // }, [count]);
    // useEffect(() => {
    //     console.log("count2:", count);
    // }, [count]);
    return (
        <div>
            <p>count:{count}</p>
            <button
                onClick={() => {
                    setCount(count + 1);
                }}>
                count + 1
            </button>
            <div id="chart" style={{ width: "40vw", height: 500 }}></div>
            <button
                onClick={() => {
                    const data = [
                        random(0, 20),
                        random(0, 20),
                        random(0, 20),
                        random(0, 20),
                        random(0, 20),
                        random(0, 20),
                    ];
                    const newOption = cloneDeep(option);
                    newOption.series[0].data = data;
                    setOption(newOption);
                }}>
                修改图表数据
            </button>
        </div>
    );
}

export default App;
